package com.home.webapp.base.service.impl;

import com.home.base.core.framework.msg.PageResponse;
import com.home.common.framework.core.service.impl.BaseServiceImpl;
import com.home.common.handler.exception.BizException;
import com.home.common.utils.query.QueryParams;
import com.home.webapp.base.entity.BaseDictData;
import com.home.webapp.base.entity.BaseDictType;
import com.home.webapp.base.mapper.BaseDictDataMapper;
import com.home.webapp.base.mapper.BaseDictTypeMapper;
import com.home.webapp.base.service.BaseDictTypeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Description: 字典类型表 serviceImpl
 * Created by 王大宸 on 2020-10-05 23:28:38
 * Created with IntelliJ IDEA.
 */
@Service
public class BaseDictTypeServiceImpl extends BaseServiceImpl<BaseDictTypeMapper, BaseDictType, String> implements BaseDictTypeService {
    private static final Logger logger = LoggerFactory.getLogger(BaseDictTypeServiceImpl.class);
    @Autowired
    private BaseDictDataMapper dictDataMapper;

    /***
     * 功能说明：分页
     *
     * @author 王大宸
     * @date 2020/11/25 23:11
     * @param params
     * @return com.home.common.framework.msg.PageResponse
     */
    @Override
    public PageResponse<BaseDictType> page(Map<String, Object> params) {
        QueryParams queryParams = new QueryParams(params);
        Page<BaseDictType> page = PageHelper.startPage(queryParams.getPage(), queryParams.getLimit());
        List<BaseDictType> list = baseMapper.page(queryParams);
        return PageResponse.ok(page.getTotal(), list);
    }

    /***
     * 功能说明：删除数据字典类型
     *
     * @author 王大宸
     * @date 2020/10/15 0:55
     * @param id 需要删除的字典id
     * @return com.home.common.framework.msg.ServerResponse<com.home.webapp.base.entity.BaseDictType>
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int remove(String id) throws BizException {
        BaseDictType baseDictType = baseMapper.selectByPrimaryKey(id);
        if (null == baseDictType) {
            throw new BizException("数据不存在,请刷新表格");
        }

        BaseDictData dictData = new BaseDictData();
        dictData.setDictType(baseDictType.getDictType());
        List<BaseDictData> select = dictDataMapper.select(dictData);
        if (null != select && 0 < select.size()) {
            throw new BizException("数据字典【" + baseDictType.getDictName() + "】有" + select.size() + "条数据,请先删除数据字典");
        }
        return super.remove(id);
    }

}
